from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView,ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework import mixins

# POST /meiduo_admin/authorizations/
from meiduo_admin.serializers.users import AdminAuthSerializer, UserInfoSerializer
from users.models import User


class AdminAuthorizeView(APIView):

    def post(self, request):
        """
        管理员登录
        1.获取参数并校验(参数完整性;用户名或者密码是否正确)
        2.服务器需要生成jwt token
        3.返回相应数据,登录成功
        """
        # 获取参数并校验
        serializer = AdminAuthSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 服务器需要生成jwt token
        serializer.save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)


# GET /meiduo_admin/users/?keyword=<搜索内容>&page=<页码>&pagesize=<页容量>
# class UserInfoView(mixins.ListModelMixin, GenericAPIView):
class UserInfoView(ListAPIView):
    permission_classes = [IsAdminUser]

    serializer_class = UserInfoSerializer

    def get_queryset(self):
        '''重写父类中get_queryset'''
        keyword = self.request.query_params.get('keyword')
        if keyword:
            # 1.1 如果传递了keyword, 查询用户名中有keyword的用户
            users = User.objects.filter(is_staff=False, username__contains=keyword)
        else:
            # 1.2  如果没有传递了keyword, 查询所有普通用户的数据
            users = User.objects.filter(is_staff=False)

        return users

    # def get(self, request):
    #     '''
    #     self.request :请求对象
    #     普通用户数据的获取
    #     1.查询数据库获取普通用户的数据
    #         1.1 如果传递了keyword,查询用户名中有keyword的用户
    #         1.2 如果没有传递了keyword,查询所有普通用户的数据
    #     2.将普通用户数列化并返回
    #     '''
    #     # # 查询数据库获取普通用户的数据
    #     # users = self.get_queryset()
    #     # # 将普通用户数列化并返回
    #     # serializer = self.get_serializer(users, many=True)
    #     # return Response(serializer.data)
    #     return self.list(request)
